#!/usr/bin/python -u

import sys, getopt, syslog

MACSPELL = '@(#) International Ispell Version 3.1.20 (but really MacSpell 2011)'

Config = {
    'terse_mode': False
}

def get_line():
    line = sys.stdin.readline()
    return unicode(line, 'utf-8')

get_lines = sys.stdin.readlines

def check_spelling(checker, string, start=0):
    from Cocoa import NSString
    _string = NSString.stringWithString_(string)
    _range, _count = checker.checkSpellingOfString_startingAt_language_wrap_inSpellDocumentWithTag_wordCount_(_string, start, None, False, 0, None)
    syslog.syslog(syslog.LOG_ERR, 'Checked: %s range: %s count: %d' % (string.encode('utf-8'), _range, _count))
    if _range.length == 0:
        syslog.syslog(syslog.LOG_ERR, 'OK')
        return True, _count, None, None
    else:
        word = string[_range.location:_range.location+_range.length]
        syslog.syslog(syslog.LOG_ERR, 'Misspelled: %s' % word.encode('utf-8'))
        return False, _count, _range, word

def guesses(checker, string, _range):
    from Cocoa import NSString
    _string = NSString.stringWithString_(string)
    _words = checker.guessesForWordRange_inString_language_inSpellDocumentWithTag_(_range, _string, None, 0)
    n = len(_words)
    words = u', '.join(_words) # This is unicode
    return n, words

def set_dictionary(language):
    from Cocoa import NSSpellChecker
    checker = NSSpellChecker.sharedSpellChecker()
    res = checker.setLanguage_(language)
    if res:
        syslog.syslog(syslog.LOG_ERR, 'Selected %s dictionary' % language)
    else:
        syslog.syslog(syslog.LOG_ERR, 'Invalid dictionary: %s' % language)

def pipe_mode(checker):
    syslog.syslog(syslog.LOG_ERR, 'Entered into pipe mode: %s' % checker)
    print MACSPELL
    while True:
        line = get_line()
        if len(line) == 0: break
        if line == '\n': continue
        prefix = line[0]
        if prefix == '!':
            syslog.syslog(syslog.LOG_ERR, 'Terse mode ON')
            Config['terse_mode'] = True
            continue
        if prefix == '%':
            syslog.syslog(syslog.LOG_ERR, 'Terse mode OFF')
            Config['terse_mode'] = False
            continue
        if prefix == '-':
            syslog.syslog(syslog.LOG_ERR, 'Obsolete -')
            continue
        syslog.syslog(syslog.LOG_ERR, 'Got line: %s' % line.encode('utf-8'))
        last = 0
        while True:
            ok, count, _range, word = check_spelling(checker, line, last)
            if ok:
                if Config['terse_mode'] == False:
                    for x in range(count):
                        print '*'
                break
            else:
                last = _range.location + _range.length
                n, words = guesses(checker, line, _range)
                if Config['terse_mode'] == False:
                    for x in range(count-1):
                        print '*'
                if n == 0:
                    print '#', word.encode('utf-8'), _range.location
                else:
                    print '&', word.encode('utf-8'), '%d %d:' % (n, _range.location), words.encode('utf-8')
        print

def main(argv=None):
    if argv == None:
        argv = sys.argv
    syslog.syslog(syslog.LOG_ERR, 'Started MacSpell with args %s' % argv[1:])
    try:
        opts, args = getopt.getopt(argv[1:], 'v:amBCd:', ('version', 'pipe'))
    except getopt.error, msg:
        print >> sys.stderr, msg[0]
        return 2
    enter_pipe = False
    for opt, arg in opts:
        if opt in ('-v', '--version'):
            print MACSPELL
            return 0
        if opt in ('-a', '--pipe'):
            enter_pipe = True
        if opt in ('-m', '-B', '-C'):
            pass
        if opt in ('-d'):
            set_dictionary(arg)
    if enter_pipe:
        from Cocoa import NSSpellChecker
        checker = NSSpellChecker.sharedSpellChecker()
        pipe_mode(checker)
    return 0

if __name__ == '__main__':
    sys.exit(main())
